import re
# import requests
from curl_cffi import requests
import os
import shutil

if os.path.exists('static/彼岸图网'):
    shutil.rmtree('static/彼岸图网')
os.mkdir('static/彼岸图网')



total_url = 'https://pic.netbian.com'


headers = {
	'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
    'Referer': 'https://pic.netbian.com/',
}

for page in range(1,20):
	if page == 1:
		url = 'https://pic.netbian.com/index.html'
	else:
		url = 'https://pic.netbian.com/index_%s.html'%page
	if os.path.exists(f'static/彼岸图网/{page}'):
		shutil.rmtree(f'static/彼岸图网/{page}')
	os.mkdir(f'static/彼岸图网/{page}')
	
	# 使用Session保持会话
	session = requests.Session()
	session.headers.update(headers)
	
	response = session.get(url)
	data = response.content.decode('gbk')
	
	data_info = re.findall(r'<li><a href="(/tupian/\d{5}.html)" title="(.*?)" target="_blank"><span><img src="(.*?)".*?</li>',data,re.S)
	if data_info:
		for data in data_info:
			datil_url = total_url + data[0]
			title = data[1].strip()
			img_url = total_url + data[2]
			print(datil_url,title, img_url)
			img_response = requests.get(img_url,headers=headers)
			with open(f'static/彼岸图网/{page}/{title}.jpg', 'wb') as f:
				f.write(img_response.content)
	else:
		data_info = re.findall(r'<li><a href="(/tupian/\d{5}.html)" target="_blank"><img src="(.*?)" alt="(.*?)".*?</a></li>', data, re.S)
		for data in data_info:
			datil_url = total_url + data[0]
			title = data[2]
			img_url = total_url + data[1]
			print(datil_url,title, img_url)
			img_response = requests.get(img_url, headers=headers)
			with open(f'static/彼岸图网/{page}/{title}.jpg', 'wb') as f:
				f.write(img_response.content)


